package com.woniuxy.service.impl;

import cn.hutool.core.util.ReUtil;
import com.woniuxy.entity.po.JobBean;
import com.woniuxy.job.MyJob;
import com.woniuxy.mapper.LogMapper;
import com.woniuxy.service.LogService;
import com.woniuxy.service.QuartzService;
import com.woniuxy.util.JobUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @BelongsProject: quartzStudy
 * @BelongsPackage: com.woniuxy.controller
 * @Author: Quan
 * @Date: 2025/3/4 17:58
 */
//@RestController
//@RequestMapping("/quartz")
@Service
public class QuartzServiceImpl implements QuartzService {
	@Autowired
	private Scheduler scheduler;

	@Autowired
	private LogService logService;

	@Autowired
	private LogMapper logMapper;

	private final String jobName = "myJob";

	@Value("${quartz.cron-exception}")
	private String cronException;
	private final String reg = "/(\\d+)"; // 使用捕获组匹配 / 后面的数字

	@Autowired
	HttpServletRequest request;

	//	@GetMapping("/create")
	@Override
	public String createJob() throws SchedulerException, ClassNotFoundException {
		JobBean jobBean = new JobBean(jobName, MyJob.class.getName(), cronException);
		JobUtils.createJob(scheduler, jobBean);
		return "任务创建成功";
	}

	//	@GetMapping("pause")
	@Override
	public String pauseJob() throws SchedulerException {
		JobUtils.pauseJob(scheduler, jobName);
		return "任务暂停成功";
	}

	@Override
//	@GetMapping("resume")
	public String resumeJob() throws SchedulerException {
		JobUtils.resumeJob(scheduler, jobName);
		return "任务恢复成功";
	}

	@Override
//	@GetMapping("delete")
	public String deleteJob() throws SchedulerException {
		JobUtils.deleteJob(scheduler, jobName);
		return "任务删除成功";
	}

	@Override
//	@GetMapping("once")
	public String runOnceJob() throws SchedulerException {
		JobUtils.runOnceJob(scheduler, jobName);
		return "任务执行一次就成功";
	}

	@Override
//	@GetMapping("modify")
	public String modifyJob(String retainTime) throws SchedulerException, IOException {
		String modifyCronException = ReUtil.replaceAll(cronException, reg, "/"+retainTime); // 替换为 /8
		JobBean jobBean = new JobBean(jobName, MyJob.class.getName(), modifyCronException);
		JobUtils.modifyJob(scheduler, jobBean);
		request.getSession().setAttribute("retainTime", retainTime);
		System.out.println("时间间隔设置成功");
		return "任务修改成功";
	}
}
